package com.dishdex.menuhub.console.controller.category;

import com.dishdex.menuhub.console.annotations.VerifiedUser;
import com.dishdex.menuhub.console.domain.category.CategoryDetailVO;
import com.dishdex.menuhub.console.domain.category.CategoryLevelOneVO;
import com.dishdex.menuhub.console.domain.category.CategoryListVO;
import com.dishdex.menuhub.console.domain.category.CategoryOperationResultVO;
import com.dishdex.menuhub.console.util.CategoryConverter;
import com.dishdex.menuhub.console.util.CategoryTreeHelper;
import com.dishdex.menuhub.module.module.category.entity.Category;
import com.dishdex.menuhub.module.module.category.service.CategoryService;
import com.dishdex.menuhub.module.module.dish.service.DishService;
import com.dishdex.menuhub.module.module.user.entity.User;
import com.dishdex.menuhub.module.utils.BaseUtils;
import com.dishdex.menuhub.module.utils.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @RequestMapping("/category/list")
    public Response categoryList(@RequestParam(value = "categoryId", required = false) Long categoryId,
                                 @VerifiedUser User loginUser) {
        if (BaseUtils.isEmpty(loginUser)) {
            return new Response(1002);
        }
        List<Category> categoryList;
        try {
            categoryList = categoryService.getAll(categoryId);
        } catch (RuntimeException e) {
            CategoryListVO categoryListVO = new CategoryListVO();
            categoryListVO.setMessage(e.getMessage());
            return new Response(4004, categoryListVO);
        }

        // 存储一级分类列表
        List<CategoryLevelOneVO> categoryLevelOneVOList = new ArrayList<>();

        // 存储一级分类映射
        Map<Long, CategoryLevelOneVO> levelOneCategoryMap = new HashMap<>();

        //获取一级分类Id
        List<Long> levelOneCategoryIds = categoryService.getLevelOneIds();

        /*
         * 先将一级分类进行处理，即先寻找一级分类，并将其转化为VO，存储到列表中和Map中；
         * */
        for (Category category : categoryList) {
            if (levelOneCategoryIds.contains(category.getId())) {
                //找到一级分类后，将其转换为VO，并进行存储
                CategoryLevelOneVO categoryLevelOneVO = CategoryConverter.toCategoryLevelOneVO(category);
                categoryLevelOneVOList.add(categoryLevelOneVO);
                levelOneCategoryMap.put(category.getId(), categoryLevelOneVO);
            }
        }

        /*
         * 寻找二级分类，并将其转换为VO，存储到一级分类中的children列表中去
         * */

        //获取二级分类Id
        List<Long> categoryLevelTwoVOList = categoryService.getLevelTwoIds();

        for (Category category : categoryList) {
            if (categoryLevelTwoVOList.contains(category.getId())) {
                //找到二级分类后，从levelOneCategoryMap取出其对应的一级分类，并将找到的二级分类添加到children列表中
                CategoryLevelOneVO categoryLevelOneVO = levelOneCategoryMap.get(category.getParentId());
                if (categoryLevelOneVO != null) {
                    categoryLevelOneVO.getChildren().add(CategoryConverter.toCategoryLevelTwoVO(category));
                }
            }
        }

        CategoryListVO categoryListVO = new CategoryListVO();
        categoryListVO.setList(categoryLevelOneVOList);
        return new Response(1001, categoryListVO);
    }

    @RequestMapping("/category/info")
    public Response categoryInfo(@RequestParam(value = "categoryId", required = false) Long id,
                                 @VerifiedUser User loginUser) {
        if (BaseUtils.isEmpty(loginUser)) {
            return new Response(1002);
        }
        Category category;
        try {
            category = categoryService.getById(id);
        } catch (RuntimeException e) {
            CategoryDetailVO categoryDetailVO = new CategoryDetailVO();
            categoryDetailVO.setMessage(e.getMessage());
            return new Response(4004, categoryDetailVO);
        }
        CategoryDetailVO categoryDetailVO = new CategoryDetailVO()
                .setCategoryName(category.getCategoryName() == null ? "" : category.getCategoryName())
                .setCategoryImage(category.getCategoryImage() == null ? "" : category.getCategoryImage())
                .setParentId(category.getParentId() == null ? -1 : category.getParentId())
                .setCreateTime(category.getCreateTime() == null ? "" : String.valueOf(category.getCreateTime()))
                .setUpdateTime(category.getUpdateTime() == null ? "" : String.valueOf(category.getUpdateTime()));
        return new Response(1001, categoryDetailVO);
    }

    @RequestMapping("/category/update")
    public Response categoryUpdate(
            @RequestParam(value = "categoryId", required = false) Long id,
            @RequestParam(value = "categoryName", required = false) String categoryName,
            @RequestParam(value = "categoryImage", required = false) String categoryImage,
            @RequestParam(value = "parentId", required = false) Long parentId,
            @VerifiedUser User loginUser) {
        if (BaseUtils.isEmpty(loginUser)) {
            return new Response(1002);
        }
        Long result;
        try {
            result = categoryService.update(
                    id,
                    categoryName,
                    categoryImage,
                    parentId);
        } catch (RuntimeException e) {
            CategoryOperationResultVO categoryOperationResultVO = new CategoryOperationResultVO();
            categoryOperationResultVO.setMessage(e.getMessage());
            return new Response(4004, categoryOperationResultVO);
        }
        CategoryOperationResultVO categoryOperationResultVO = new CategoryOperationResultVO();
        categoryOperationResultVO.setMessage(String.valueOf(result));
        return new Response(1001, categoryOperationResultVO);
    }

    @RequestMapping("/category/insert")
    public Response categoryInsert(
            @RequestParam(value = "categoryName", required = false) String categoryName,
            @RequestParam(value = "categoryImage", required = false) String categoryImage,
            @RequestParam(value = "parentId", required = false) Long parentId,
            @VerifiedUser User loginUser) {
        if (BaseUtils.isEmpty(loginUser)) {
            return new Response(1002);
        }
        Long result;
        try {
            result = categoryService.insert(
                    categoryName,
                    categoryImage,
                    parentId);
        } catch (RuntimeException e) {
            CategoryOperationResultVO categoryOperationResultVO = new CategoryOperationResultVO();
            categoryOperationResultVO.setMessage(e.getMessage());
            return new Response(4004, categoryOperationResultVO);
        }
        CategoryOperationResultVO categoryOperationResultVO = new CategoryOperationResultVO();
        categoryOperationResultVO.setMessage(String.valueOf(result));
        return new Response(1001, categoryOperationResultVO);
    }

    @Autowired
    private DishService dishService;

    @RequestMapping("/category/delete")
    public Response categoryDelete(@RequestParam(value = "categoryId", required = false) Long id,
                                   @VerifiedUser User loginUser) {
        if (BaseUtils.isEmpty(loginUser)) {
            return new Response(1002);
        }
        int result;
        try {
            dishService.deleteByCategoryId(id);
            result = categoryService.delete(id);
        } catch (RuntimeException e) {
            CategoryOperationResultVO categoryOperationResultVO = new CategoryOperationResultVO();
            categoryOperationResultVO.setMessage(e.getMessage());
            return new Response(4004, categoryOperationResultVO);
        }
        CategoryOperationResultVO categoryOperationResultVO = new CategoryOperationResultVO();
        categoryOperationResultVO.setMessage(result == 1 ? "成功" : "失败");
        return new Response(1001, categoryOperationResultVO);
    }

    @RequestMapping("/category/tree")
    public Response categoryTree(@VerifiedUser User loginUser) {
        if (BaseUtils.isEmpty(loginUser)) {
            return new Response(1002);
        }
        List<Category> categoryList = categoryService.getAll(null);
        //构建groupMap，即按parentId对Category进行分组，方便找孩子列表
        Map<Long, List<Category>> groupMap = new HashMap<>();
        for (Category category : categoryList) {
            Long parentId = category.getParentId();
            List<Category> tempList = groupMap.get(parentId);
            if (tempList == null) {
                tempList = new ArrayList<>();
                groupMap.put(parentId, tempList);
            }
            tempList.add(category);
        }

        //构建分类树
        //提取一级分类，即parentId=0的List<Category>
        List<Category> levelOneList = groupMap.get(0L);
        List<CategoryLevelOneVO> levelOneVOList = new ArrayList<>();
        for (Category category : levelOneList) {
            CategoryLevelOneVO categoryLevelOneVO = new CategoryLevelOneVO()
                    .setId(category.getId() == null ? -1 : category.getId())
                    .setCategoryImage(category.getCategoryImage() == null ? "" : category.getCategoryImage())
                    .setCategoryName(category.getCategoryName() == null ? "" : category.getCategoryName())
                    .setChildren(CategoryTreeHelper.getChildren(category.getId(), groupMap));
            levelOneVOList.add(categoryLevelOneVO);
        }
        CategoryListVO categoryListVO = new CategoryListVO();
        categoryListVO.setList(levelOneVOList);
        return new Response(1001, categoryListVO);
    }

}